import { getToken, setToken, removeToken } from "@/utils/auth";
import router, { resetRouter } from "@/router";
import mmUrl from "@/utils/utilUrl";
import axios from "axios";
const state = {
  token: getToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [""],
  Authorization: ""
};

const mutations = {
  SET_Authorization: (state, Authorization) => {
    state.Authorization = Authorization;
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles;
  }
};
const actions = {
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      userInfo.current
        .$post({
          url: mmUrl.login.login,
          data: {
            passWord: userInfo.info.password,
            userCode: userInfo.info.username.trim()
          }
        })
        .then(res => {
          commit("SET_Authorization", res);
          commit("SET_TOKEN", "admin-token");
          setToken("admin-token");
          sessionStorage.setItem("Bearer", res);
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },
  setUserInfo({ commit }) {
    let data;
    data = JSON.parse(sessionStorage.getItem("userInfo"));
    axios.defaults.headers.common["Authorization"] = sessionStorage.getItem(
      "Bearer"
    );
    if (!data) {
      axios.defaults.headers.common["Authorization"] = sessionStorage.getItem(
        "Bearer"
      );
      axios.get("/manage/user/getCurrentUser").then(res => {
        const data = Object.assign(
          {
            avatar: res.data.data.userName,
            introduction: "I am a super administrator",
            roles: ["admin"]
          },
          {
            name: res.data.data.userName
          }
        );
        sessionStorage.setItem("userInfo", JSON.stringify(data));
        const { roles, name, avatar, introduction } = data;
        commit("SET_ROLES", roles);
        commit("SET_NAME", name);
        commit("SET_AVATAR", avatar);
        commit("SET_INTRODUCTION", introduction);
      });
      return;
    }
    const { roles, name, avatar, introduction } = data;
    commit("SET_ROLES", roles);
    commit("SET_NAME", name);
    commit("SET_AVATAR", avatar);
    commit("SET_INTRODUCTION", introduction);
  },
  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      if (state.Authorization) {
        axios.defaults.headers.common["Authorization"] =
          "Bearer " + state.Authorization;
        axios.defaults.headers.common["os"] = "Bearer " + 2;
        axios.get("/manage/user/getCurrentUser").then(res => {
          const data = Object.assign(
            {
              avatar: res.data.data.userName,
              introduction: "I am a super administrator",
              roles: ["admin"]
            },
            {
              name: res.data.data.userName
            }
          );
          sessionStorage.setItem("userInfo", JSON.stringify(data));
          if (!data) {
            reject("Verification failed, please Login again.");
          }
          const { roles, name, avatar, introduction } = data;
          // roles must be a non-empty array
          if (!roles || roles.length <= 0) {
            reject("getInfo: roles must be a non-null array!");
          }
          commit("SET_ROLES", roles);
          commit("SET_NAME", name);
          commit("SET_AVATAR", avatar);
          commit("SET_INTRODUCTION", introduction);
          resolve(data);
        });
      } else {
        reject(error);
      }
    });
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      axios
        .post(mmUrl.login.out, {})
        .then(() => {
          commit("SET_TOKEN", "");
          commit("SET_ROLES", []);
          removeToken();
          resetRouter();
          sessionStorage.clear();
          resolve();
        })
        .catch(error => {
          reject(error);
        });
    });
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit("SET_TOKEN", "");
      commit("SET_ROLES", []);
      removeToken();
      resolve();
    });
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + "-token";

      commit("SET_TOKEN", token);
      setToken(token);

      const { roles } = await dispatch("getInfo");

      resetRouter();

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch("permission/generateRoutes", roles, {
        root: true
      });

      // dynamically add accessible routes
      router.addRoutes(accessRoutes);

      // reset visited views and cached views
      dispatch("tagsView/delAllViews", null, {
        root: true
      });

      resolve();
    });
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};
